package com.solution.pc.order.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.constants.OrderConstants.ORDER_PAY_MODEL;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.service.OrderService;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.swiftpass.MD5;
import com.solution.common.swiftpass.SignUtils;
import com.solution.common.swiftpass.SwiftpassConfig;
import com.solution.common.swiftpass.SwiftpassPayVO;
import com.solution.common.swiftpass.XmlUtils;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.config.AlipayConfig;
import com.solution.pc.order.entity.OrderAlipayNotifyLogEntity;
import com.solution.pc.order.service.OrderAlipayNotifyLogService;
import com.solution.pc.order.task.OrderPayStatusUpdateTask;
import com.solution.pc.order.task.OrderStatusFixedThreadPool;

/**
 * 支付宝支付网关
 * @author llp
 */
@RequestMapping("/pc/alipay")
@Controller
public class AliOrderPayController extends BaseController{
	
	Logger log = Logger.getLogger(AliOrderPayController.class);
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderAlipayNotifyLogService orderAlipayNotifyLogService;
	
	/**
	 * 订单支付
	 * @param httpRequest
	 * @param httpResponse
	 * @throws IOException
	 * @author llp
	 */
	@RequestMapping("/payOrder")
	public void aliPayOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", 
				AlipayConfig.app_id, 
				AlipayConfig.merchant_private_key, 
				AlipayConfig.format,
				AlipayConfig.charset,
				AlipayConfig.alipay_public_key,
				AlipayConfig.sign_type); //获得初始化的AlipayClient
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
		
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);//在公共参数中设置回跳和通知地址
		// passback_params 回传参数
		
		// 查询订单信息进行支付
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderCode", request.getParameter("orderCode"));
		List<OrderEntity> orderList = orderService.listOrder(param);
		OrderEntity order = null;
		if(orderList != null && orderList.size() > 0){
			order = orderList.get(0);
		}else{
			
		}
		
		StringBuffer subjectBuf = new StringBuffer();
		String productDetail = order.getProductDetail();
		if(StringUtil.isNotEmpty(productDetail)){
			// 将商品详情json串转化为 OrderDetailEntity 列表
			String productDetailJsonStr = "["+productDetail+"]";
			List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
			order.setProductList(orderDetailList);
		}
		
		subjectBuf.append(order.getProductList().get(0).getProductName()).append(order.getProductList().size() > 1 ? "...":"");

		//创建订单交易记录
		String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
		String outTradeNo = "ali"+OrderConstants.ORDER_CHANNEL.PC.getCode()
				+String.valueOf(System.currentTimeMillis()).substring(3)
				+currentUserCode.substring(currentUserCode.length()-4);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", order.getOrderCode());
		paramMap.put("outTradeNo", outTradeNo);
		paramMap.put("creater", getUserName());
		try {
			// 订单中关键了自定义支付订单号，为了应对订单调价后无法支付的情况 
			orderService.saveOrderTrade(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		alipayRequest.setBizContent("{" +
				"    \"out_trade_no\":\""+outTradeNo+"\"," +
				"    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
				"    \"total_amount\":"+order.getRealPayMoney()+"," +
				"    \"subject\":\"景旭商城订单支付\"," +
				"    \"body\":\""+subjectBuf.toString()+"\"," +
				"    \"passback_params\":\"JXSC\"," +
				"    \"extend_params\":{" +
				"    \"sys_service_provider_id\":\""+AlipayConfig.app_id+"\"" +
				"    }"+
				"  }");//填充业务参数
		String form="";
		try {
			form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
		} catch (AlipayApiException e) {
		e.printStackTrace();
		}
		response.setContentType("text/html;charset=" + AlipayConfig.charset);
		//直接将完整的表单html输出到页面
		response.getWriter().write(form);
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	/**
	 * 支付宝异步通知
	 * @param request
	 * @return
	 * @author llp
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/alipayNotify")
	@ResponseBody
	public String alipayNotify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		// 待验签参数
		Map<String,String> params = new HashMap<String,String>();
		// 请求参数(获取支付宝POST过来反馈信息)
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		//获取交易流水对应的订单号
		String orderCode = orderService.getOrderCodeByOutTradeNo(params.get("out_trade_no"));
		
		// 记录异步通知的日志
		OrderAlipayNotifyLogEntity alipayLog = new OrderAlipayNotifyLogEntity();
		alipayLog.setOrderCode(orderCode);
		alipayLog.setTradeNo(params.get("trade_no"));
		alipayLog.setBuyerPayAmount(new BigDecimal(params.get("buyer_pay_amount")));
		alipayLog.setReceiptAmount(new BigDecimal(params.get("receipt_amount")));
		alipayLog.setNotifyType("01");  // 01 异步 02 同步
		alipayLog.setNotifyTime(DateUtils.getStringDateTime(params.get("notify_time"), "yyyy-MM-dd HH:mm:ss"));
		alipayLog.setTradeStatus(params.get("trade_status"));
		alipayLog.setNotifyContent(JSONObject.toJSONString(params));
		alipayLog.setRsaCheckTime(new Date());
		// 调用SDK验证签名
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, 
					AlipayConfig.charset, AlipayConfig.sign_type.toUpperCase());
			if(signVerified){
				alipayLog.setRsaCheckResult("success");
				
				// 插入订单支付记录，并修改订单状态为支付成功
				OrderPayEntity orderPay = new OrderPayEntity();
				orderPay.setOrderCode(orderCode);
				orderPay.setPayCode(params.get("trade_no"));
				orderPay.setPayTime(DateUtils.getStringDateTime(params.get("notify_time"), "yyyy-MM-dd HH:mm:ss"));
				orderPay.setPayMoney(new BigDecimal(params.get("receipt_amount")));
				orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.ALIPAY.getCode());
				orderPay.setConfirmStatus(OrderConstants.ORDER_PAY_CONFIRM_STATUS.NOT_CONFIRM.getCode());
				orderPay.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
				orderPay.setCreater("system");
				orderPay.setCreateTime(new Date());
				
				Map<String, Object> payParam = new HashMap<String, Object>();
				payParam.put("orderPay", orderPay);
				payParam.put("orderCode", orderCode);
				
				// 支付成功，修改订单状态(立即付款进入待审核，货到付款进入待核销)
				OrderEntity order = orderService.getOrderByCode(orderCode);
				if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
				} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
				} else {
					//支付方式错误,进入待审核
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
				}
				
				//支付成功，订单改为已支付状态
				payParam.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
				payParam.put("payTime", DateUtils.getStringDateTime(params.get("notify_time"), "yyyy-MM-dd HH:mm:ss"));

				//记录日志
				OrderLogEntity orderLog = new OrderLogEntity();
				orderLog.setOrderCode(orderCode);
				orderLog.setOperaterCode("");
				orderLog.setOperaterName("支付宝支付通知");
				orderLog.setOpTime(new Date());
//				orderLog.setLogType(logType);
				orderLog.setLogContent("支付订单成功");
				orderLog.setCreater("支付宝支付通知");
				payParam.put("orderLogEntity", orderLog);
				
				// 异步执行更新订单状态，不影响支付宝接口返回
				OrderPayStatusUpdateTask opsuTask = new OrderPayStatusUpdateTask(payParam);
				opsuTask.setOrderService(orderService);
				OrderStatusFixedThreadPool.addTask(opsuTask);
				
				/**
				 * 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，
				 * 校验成功后在response中返回success并继续商户自身业务处理，
				 * 校验失败返回failure
				 */
				return "success";
				
			}else{
				// 验签失败则记录异常日志，并在response中返回failure.
				alipayLog.setRsaCheckResult("failure");
				// 记录异步通知日志
				return "failure";
			}
		} catch (AlipayApiException e) {
			alipayLog.setRsaCheckResult("failure");
			alipayLog.setRsaBizCheckReason(e.getMessage());
			e.printStackTrace();
			return "failure";
		}finally{
			// 记录异步通知日志
			orderAlipayNotifyLogService.saveOrderAlipayNotifyLog(alipayLog);
		}
	}
	
	/**
	 * 支付宝支付成功同步跳转页面
	 * @return
	 * @throws AlipayApiException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/alipayResult")
	public String alipayRedirect(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException{
		
		Map<String, String> paramsMap = new HashMap<String, String>();
        // eg:String resultInfo ="gmt_create=2017-06-27 15:38:45&charset=UTF-8&seller_email=panch198@163.com&subject=测试订单&sign=eV1dZxV1mtSK+7IB/pfBBiaMSGPKY3zk/fJYflcc7XahwT9F7lXewwePebxO3cPp00PC1pUlkMRajIJKHHompojSFXsUdLc2pLtSrghnxMi+Q/W7HxIHAl4dnKkmUU890qFequkBoqnrlrcgcobNZOKv4i4RtsDFxDDyy2aTyb7yi8NW30muSvT9kcOr96hEtxnIDMgXxU4I76My5cqyiCgV3wRzpZeiVoURrRnLem1WDIImJ2+LEwuE8VLcyJs/jWEAEwFKpKKE8r5rZ9NeCAyLe47a9pP2IvPUmF8IMrzVCzaNn2sUDpwEJQk8Bn6yOiXLVNBGMbP7Myi1/1qs+Q==&body=测试订单内容&buyer_id=2088112008646530&invoice_amount=0.01&notify_id=cd46801bb75798a5adbbd7458045548k3a&fund_bill_list=[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]&notify_type=trade_status_sync&trade_status=TRADE_SUCCESS&receipt_amount=0.01&app_id=2016082601806424&buyer_pay_amount=0.01&sign_type=RSA2&seller_id=2088812720933216&gmt_payment=2017-06-27 15:38:46&notify_time=2017-06-27 16:02:31&version=1.0&out_trade_no=149854908578621066&total_amount=0.01&trade_no=2017062721001004530210421009&auth_app_id=2016082601806424&buyer_logon_id=177****6223&point_amount=0.00";
		log.debug("解码前：queryString" + request.getQueryString());
		String resultInfo = URLDecoder.decode(request.getQueryString(), AlipayConfig.charset);
		log.debug("解码前：queryString" + resultInfo);
		
		String outTradeNo = null;
		String[] tmpArrs = resultInfo.split("&");
		for (String tmpArr : tmpArrs) {
			String[] kvArrs = tmpArr.split("=");
			if(StringUtil.isNotEmpty(kvArrs[0]) && StringUtil.isNotEmpty(kvArrs[1])){
				paramsMap.put(kvArrs[0], kvArrs[1]);
				// 提取订单号
				if("out_trade_no".equals(kvArrs[0])){
					outTradeNo = kvArrs[1];
				}
				log.debug("支付宝接口同步通知返回参数："+kvArrs[0]+"="+kvArrs[1]);
			}
		}
		String sign = request.getParameter("sign");
        paramsMap.put("sign",sign);
		
		// 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, 
				AlipayConfig.charset,
				AlipayConfig.sign_type.toUpperCase()); 		
        log.debug("验签结果："+signVerified);

		//获取交易流水对应的订单号
        if(StringUtil.isNotEmpty(outTradeNo)){
        	String orderCode = orderService.getOrderCodeByOutTradeNo(outTradeNo);
        	// 查询订单信息
        	Map<String, Object> param = new HashMap<String, Object>();
        	param.put("orderCode", orderCode);
        	List<OrderEntity> orderList = orderService.listOrder(param);
        	if(orderList != null && orderList.size() > 0){
        		request.setAttribute("order", orderList.get(0));
        	}
        }
        if(signVerified){
        	return "/pc/order/pay_result";
        }else{
        	return "/pc/order/pay_error";
        }
	}
	
	
	/**
	 * 北京银行微信支付
	 * @param request
	 * @throws Exception 
	 */
	@RequestMapping("/swift/payOrder")
	@ResponseBody
	public SwiftpassPayVO swiftpassAliPay(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		// 返回结果
		SwiftpassPayVO swiftpassPayVO = new SwiftpassPayVO();
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		SortedMap<String, String> map = new TreeMap<String, String>();
		// 查询订单信息进行支付
		String orderCode = req.getParameter("orderCode");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderCode", orderCode);
		List<OrderEntity> orderList = orderService.listOrder(param);
		OrderEntity order = orderList.get(0);
		
		
		//创建订单交易记录,生成新的临时订单号，用于调价支付
		String currentUserCode = getUserCode();
		String outTradeNo = "ali"+OrderConstants.ORDER_CHANNEL.PC.getCode()
				+String.valueOf(System.currentTimeMillis()).substring(3)
				+currentUserCode.substring(currentUserCode.length()-4);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", order.getOrderCode());
		paramMap.put("outTradeNo", outTradeNo);
		paramMap.put("creater", getUserName());
		try {
			// 订单中关键了自定义支付订单号，为了应对订单调价后无法支付的情况 
			orderService.saveOrderTrade(paramMap);
		} catch (Exception e) {
			log.error(e.getMessage());
			swiftpassPayVO.setPrePayStatus("1");
            swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
            return swiftpassPayVO;
		}
		
		map.put("service", "pay.alipay.native");
		// 商品订单号
		map.put("out_trade_no", outTradeNo);
		// 商户号
		map.put("body", "景旭分销商城订单");
		// 支付客户端IP
		map.put("mch_create_ip", SwiftpassConfig.getMchCreateIp());
		// 商户号
		map.put("mch_id", SwiftpassConfig.getMchId());
		// 支付金额，单位为分
		map.put("total_fee", String.valueOf((order.getRealPayMoney().multiply(new BigDecimal(100))).intValue()));
		// 异步通知地址
	    map.put("notify_url", SwiftpassConfig.getAliPayNotifyUrl());
	    // 支付随机数
	    map.put("nonce_str", String.valueOf(new Date().getTime()));
	    // 操作员编号，这是我们放入原始订单号，方便在银行的商户后台对账查询
	    map.put("op_user_id", orderCode);
	    // 参数签名
	    Map<String,String> params = SignUtils.paraFilter(map);
	    StringBuilder buf = new StringBuilder((params.size() +1) * 10);
	    SignUtils.buildPayParams(buf,params,false);
	    String preStr = buf.toString();
	    String sign = MD5.sign(preStr, "&key=" + SwiftpassConfig.getKey(), "utf-8");
	    // 签名参数
	    map.put("sign", sign);
	    String reqUrl = SwiftpassConfig.getPayReqUrl();
	    System.out.println("reqParams:" + XmlUtils.parseXML(map));
	    
	    CloseableHttpResponse response = null;
	    CloseableHttpClient client = null;
	    String res = null;
	    try {
	        HttpPost httpPost = new HttpPost(reqUrl);
	        StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map),"utf-8");
	        httpPost.setEntity(entityParams);
	        httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
	        client = HttpClients.createDefault();
	        response = client.execute(httpPost);
	        if(response != null && response.getEntity() != null){
	            Map<String,String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
	            res = XmlUtils.toXml(resultMap);
	            System.out.println("请求结果：" + res);
	            if("Order paid".equals(resultMap.get("err_code"))){
	            	swiftpassPayVO.setPrePayStatus("1");
                    swiftpassPayVO.setErrorMessage("订单已支付，请勿重复支付!");
	            	return swiftpassPayVO;
	            }
	            if(resultMap.containsKey("sign")){
	                if(!SignUtils.checkParam(resultMap, SwiftpassConfig.getKey())){
	                    swiftpassPayVO.setPrePayStatus("1");
	                    swiftpassPayVO.setErrorMessage("验证签名不通过");
	                }else{
	                    if("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))){
	                        String codeImgUrl = resultMap.get("code_img_url");
	                        swiftpassPayVO.setCodeImgUrl(codeImgUrl);
	                        swiftpassPayVO.setOutTradeNo(order.getOrderCode());
	                        swiftpassPayVO.setTotalFee(order.getRealPayMoney());
	                        swiftpassPayVO.setPrePayStatus("0");
		                    swiftpassPayVO.setErrorMessage("生成支付二维码成功");
	                    }else{
	                    	swiftpassPayVO.setPrePayStatus("1");
		                    swiftpassPayVO.setErrorMessage(resultMap.get("message"));
	                    }
	                }
	            } 
	        }else{
	        	swiftpassPayVO.setPrePayStatus("1");
                swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
	        }
	    }catch (Exception e){
	    	log.error(e.getMessage());
	    	swiftpassPayVO.setPrePayStatus("1");
            swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
	    }
		return swiftpassPayVO;
	}
	
	/**
	 * 北京银行支付宝接口异步通知	
	 * @param req
	 * @param resp
	 */
	@RequestMapping("/swift/alipayNotify")
	@ResponseBody
	public void swiftAlipayNotify(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        String resString = XmlUtils.parseRequst(req);
        System.out.println("通知内容：" + resString);
            
        String respString = "fail";
        if(resString != null && !"".equals(resString)){
        	Map<String,String> map = XmlUtils.toMap(resString.getBytes(), "utf-8");
            String res = XmlUtils.toXml(map);
            System.out.println("通知内容：" + res);
            if(map.containsKey("sign")){
            	if(!SignUtils.checkParam(map, SwiftpassConfig.getKey())){
                	res = "验证签名不通过";
                	respString = "fail";
            	}else{
            		// 支付成功
    				handSwiftAliPaySuccess(map);
            		//此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
            		respString = "success";
            	}
            }
        }
        resp.getWriter().write(respString);
	}


	/**
	 * 支付结果处理逻辑
	 * @param params
	 */
	private boolean handSwiftAliPaySuccess(Map<String, String> params ){
		boolean flag = false;
		// 获取接口返回状态
		String status = params.get("status");
		// 业务结果
		String resultCode = params.get("result_code");
		// 获取交易流水对应的订单号
		String orderCode = orderService.getOrderCodeByOutTradeNo(params.get("out_trade_no"));
		// 记录异步通知的日志
		OrderAlipayNotifyLogEntity alipayLog = new OrderAlipayNotifyLogEntity();
		alipayLog.setOrderCode(orderCode);
		// 支付平台的交易流水号(北京银行的交易流水号)
		alipayLog.setTradeNo(params.get("transaction_id"));
		// 付款金额
		alipayLog.setBuyerPayAmount(new BigDecimal(params.get("total_fee")));
		// 收款金额
		alipayLog.setReceiptAmount(new BigDecimal(params.get("total_fee")));
		// 异步
		alipayLog.setNotifyType("01"); // 01 异步 02 同步
		// 通知时间
		alipayLog.setNotifyTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
		// 交易状态 0 -成功,非0 -失败
		alipayLog.setTradeStatus(params.get("status"));
		alipayLog.setNotifyContent(JSONObject.toJSONString(params));
		alipayLog.setRsaCheckTime(new Date());
		alipayLog.setRsaCheckResult("success");
		
		// 插入订单支付记录，并修改订单状态为支付成功
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		orderPay.setPayCode(params.get("transaction_id"));
		orderPay.setPayTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
		// 金额还原成以元为单位 
		orderPay.setPayMoney(new BigDecimal(params.get("total_fee")).divide(new BigDecimal(100)));
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.ALIPAY.getCode());
		orderPay.setConfirmStatus(OrderConstants.ORDER_PAY_CONFIRM_STATUS.NOT_CONFIRM.getCode());
		orderPay.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
		orderPay.setCreater("system");
		orderPay.setCreateTime(new Date());
		try {
			// 接口状态返回成功
			if(status != null && "0".equals(status)){
				if(resultCode != null && "0".equals(resultCode)){
					Map<String, Object> payParam = new HashMap<String, Object>();
					payParam.put("orderPay", orderPay);
					payParam.put("orderCode", orderCode);
					
					// 支付成功，修改订单状态(立即付款进入待审核，货到付款进入待核销)
					OrderEntity order = orderService.getOrderByCode(orderCode);
					if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
					} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
					} else {
						//支付方式错误,进入待审核
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
					}
					
					//支付成功，订单改为已支付状态
					payParam.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
					payParam.put("payTime", DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));

					//记录日志(插入一条支付成功的订单日志流水记录)
					OrderLogEntity orderLog = new OrderLogEntity();
					orderLog.setOrderCode(orderCode);
					orderLog.setOperaterCode("");
					orderLog.setOperaterName("支付宝支付通知");
					orderLog.setOpTime(new Date());
					orderLog.setLogContent("支付订单成功");
					orderLog.setCreater("支付宝支付通知");
					payParam.put("orderLogEntity", orderLog);
					
					// 异步执行更新订单状态，不影响支付宝接口返回
					OrderPayStatusUpdateTask opsuTask = new OrderPayStatusUpdateTask(payParam);
					opsuTask.setOrderService(orderService);
					OrderStatusFixedThreadPool.addTask(opsuTask);
				}else{
					// 接口状态返回支付失败
					alipayLog.setRsaCheckResult("failure");
				}
			}else{
				// 接口状态返回支付失败
				alipayLog.setRsaCheckResult("failure");
			}
		} catch (Exception e) {
			flag = false;
		}finally {
			// 记录异步通知日志
			orderAlipayNotifyLogService.saveOrderAlipayNotifyLog(alipayLog);
		}
		return flag;
	}
	
}
